package com.totem.base.logger.converter;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.totem.base.constants.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.helpers.MessageFormatter;

public class LogMessageConverter extends MessageConverter {

    @Override
    public String convert(ILoggingEvent event) {
        String formattedMessage = event.getFormattedMessage();
        if(formattedMessage.length() <= CommonConstants.APP_MAX_LOG_LENGTH){
            return formattedMessage;
        }

        String loggerName = event.getLoggerName();
        if(!StringUtils.startsWith(loggerName, "org.raymond")){
            return formattedMessage;
        }

        String msg = event.getMessage();
        /**
         * 三种空格:
         * \u0020,半角空格
         * \u3000,全角空格
         * \u00a0,不间断空格(no break space),html中的&nbsp
         */
        msg = msg.replaceAll("\u00a0", " ");
        msg = msg.replaceAll("\\s+", " ");
        // msg = msg.substring(StringUtils.indexOf(msg, "]"));
        // msg = msg.substring(0, CommonConstants.APP_MAX_LOG_LENGTH);
        Object[] array = event.getArgumentArray();
        if(array!=null) {
            msg = MessageFormatter.arrayFormat(msg, array).getMessage();
        }
        return msg;
    }
}
